package com.mwm.paiwei.meiye.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lianjiao.core.activity.BaseActivity;
import com.lianjiao.core.net.BaseListener;
import com.lianjiao.core.net.HttpUtil;
import com.lianjiao.core.net.RequestParams;
import com.lianjiao.core.utils.LsToast;
import com.mwm.paiwei.meiye.config.MeiYeConfig;
import com.mwm.paiwei.meiye.util.Util;
import com.mwm.paiwei.meiye.R;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;
import org.wlf.filedownloader.DownloadFileInfo;
import org.wlf.filedownloader.FileDownloader;
import org.wlf.filedownloader.base.Status;
import org.wlf.filedownloader.listener.OnDownloadFileChangeListener;
import org.wlf.filedownloader.listener.OnFileDownloadStatusListener;
import org.wlf.filedownloader.listener.simple.OnSimpleFileDownloadStatusListener;
import org.wlf.filedownloader.util.FileUtil;

import java.io.File;

import io.reactivex.functions.Consumer;
import okhttp3.Call;
import roboguice.inject.InjectView;

/**
 * Created by a1 on 2017/3/11.
 */

public class LoadingActivity extends BaseActivity {
    public final static String TAG = "LoadingActivity";
    private LoadingActivity mySelf = LoadingActivity.this;

    private RxPermissions rxPermissions;

    private float version;
    private String is_required = "";
    private String download_url = "";
    private boolean isLoadNextActivity = false;

    @InjectView(R.id.image)
    ImageView image;
    @InjectView(R.id.pb_progressbar)
    ProgressBar pb_progressbar;
    @InjectView(R.id.tv_progressbar)
    TextView tv_progressbar;
    @InjectView(R.id.ll_progressbar)
    LinearLayout ll_progressbar;

    SharedPreferences preferences = null;
    private SharedPreferences.Editor editor;

    private boolean isQzUpdate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_loading);

        preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
        editor = preferences.edit();
        MeiYeConfig.JS_VERSION = preferences.getFloat("js_version", -1);
        MeiYeConfig.JS_DOWNLOAD_URL = preferences.getString("js_download_url", "");

        isQzUpdate = getIntent().getBooleanExtra("isQzUpdate",false);


        rxPermissions = new RxPermissions(this);


        //Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            Log.e("isBoolean", "yes");
                            initJs();
                        } else {
                            finish();
                            Log.e("isBoolean", "false");
                        }
                    }
                });

        FileDownloader.registerDownloadStatusListener(mOnFileDownloadStatusListener);
        FileDownloader.registerDownloadFileChangeListener(mOnDownloadFileChangeListener);
    }

    long endTime = 0;

    private void go2Login() {


        if (System.currentTimeMillis() - endTime > 2000) {
            endTime = System.currentTimeMillis();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(LoadingActivity.this, LoginActivity.class);
                    intent.putExtra("isLoadNextActivity", isLoadNextActivity);
                    startActivity(intent);
                    finish();
                }
            }, 1000);
        }
    }

    private void getMd5() {
        String md5Str = "";
        try {
            md5Str = MeiYeConfig.getFileMD5(new File(MeiYeConfig.FILE_PATH + "/index.zip"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        String url = MeiYeConfig.url + "Api/Auth/GetAppVersionsMD5";

        final String finalMd5Str = md5Str;
        OkHttpUtils
                .get()
                .url(url)
                .addParams("versions", String.valueOf(version))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        LsToast.show(mContext, "访问异常");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            Log.e("test-one",finalMd5Str+"..."+response);
                            JSONObject object = new JSONObject(response);
                            String md5Code = object.getString("data");
                            if (TextUtils.isEmpty(md5Code) || TextUtils.isEmpty(finalMd5Str) || !md5Code.equals(finalMd5Str)) {
                                Intent intent = new Intent(LoadingActivity.this, LoadingActivity.class);
                                intent.putExtra("isQzUpdate",true);
                                startActivity(intent);
                                finish();
                            } else {
                                go2Login();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

    }

    public void initJs() {
        String url = MeiYeConfig.url + "Api/Auth/GetAppVersions";
        RequestParams params = new RequestParams();
        HttpUtil.get(params, url, new BaseListener() {
                    @Override
                    public void onError(String err) {
                        Log.e(TAG, err);
                        closeProgressDialog();
                        JSONObject json = null;
                        try {
                            json = new JSONObject(err);
                            LsToast.show(mContext, json.getString("msg"));
                        } catch (JSONException e) {
                            LsToast.show(mContext, "访问异常");
                        }
                    }

                    @Override
                    public void onComplete(String context) {
                        Log.e("TAG", context);
                        closeProgressDialog();
                        JSONObject json = null;
                        try {
                            json = new JSONObject(context);
                            SharedPreferences sp = getSharedPreferences("user", Context.MODE_PRIVATE);
                            final float js_version = sp.getFloat("js_version", -1);
                            Log.e("TAG",js_version+"..."+MeiYeConfig.JS_VERSION);
                            version = Float.parseFloat(String.valueOf(json.getJSONObject("data").getDouble("versions")));
                            is_required = json.getJSONObject("data").getString("is_required");
                            download_url = json.getJSONObject("data").getString("download_url");

                            //TODO:可能js_version要改成MeiyeConfig.JS_VERSION
                            if (version > js_version || isQzUpdate) {
                                //TODO:更新时检测是否存在包，存在就删除
                                if(Util.isFileExit(MeiYeConfig.FILE_PATH+"/index.zip")){
                                    Util.deleteFile(MeiYeConfig.FILE_PATH+"/index.zip");
                                }
                                editor.putFloat("js_version", version);
                                editor.commit();
                                Log.e("restart", preferences.getFloat("js_version", -1) + "...");
                                MeiYeConfig.JS_VERSION = version;
                                MeiYeConfig.JS_DOWNLOAD_URL = download_url;

                                image.setVisibility(View.GONE);
                                ll_progressbar.setVisibility(View.VISIBLE);
                                FileDownloader.reStart(download_url);

                            } else {
                                isLoadNextActivity = true;
                                go2Login();
                            }
                        } catch (JSONException e) {
                            LsToast.show(mContext, "数据异常");
                        }
                    }
                }
        );
    }

    private OnFileDownloadStatusListener mOnFileDownloadStatusListener = new OnSimpleFileDownloadStatusListener() {
        @Override
        public void onFileDownloadStatusRetrying(DownloadFileInfo downloadFileInfo, int retryTimes) {
            // 正在重试下载（如果你配置了重试次数，当一旦下载失败时会尝试重试下载），retryTimes是当前第几次重试
            Log.e(TAG, "onFileDownloadStatusRetrying");
        }

        @Override
        public void onFileDownloadStatusWaiting(DownloadFileInfo downloadFileInfo) {
            // 等待下载（等待其它任务执行完成，或者FileDownloader在忙别的操作）
            Log.e(TAG, "onFileDownloadStatusWaiting");
        }

        @Override
        public void onFileDownloadStatusPreparing(DownloadFileInfo downloadFileInfo) {
            // 准备中（即，正在连接资源）
            Log.e(TAG, "onFileDownloadStatusPreparing");
        }

        @Override
        public void onFileDownloadStatusPrepared(DownloadFileInfo downloadFileInfo) {
            // 已准备好（即，已经连接到了资源）
            Log.e(TAG, "onFileDownloadStatusPrepared");
        }

        @Override
        public void onFileDownloadStatusDownloading(DownloadFileInfo downloadFileInfo, float downloadSpeed, long remainingTime) {
            // 正在下载，downloadSpeed为当前下载速度，单位KB/s，remainingTime为预估的剩余时间，单位秒
            Log.e(TAG, "onFileDownloadStatusDownloading");

            // download progress
            int totalSize = (int) downloadFileInfo.getFileSizeLong();
            int downloaded = (int) downloadFileInfo.getDownloadedSizeLong();
            int rate = (int) (downloaded * 1.0 / totalSize * 100);
            pb_progressbar.setProgress(rate);
            tv_progressbar.setText("下载进度" + rate + "%");
        }

        @Override
        public void onFileDownloadStatusPaused(DownloadFileInfo downloadFileInfo) {
            // 下载已被暂停
            Log.e(TAG, "onFileDownloadStatusPaused");
        }

        @Override
        public void onFileDownloadStatusCompleted(DownloadFileInfo downloadFileInfo) {
            // 下载完成（整个文件已经全部下载完成）
            Log.e(TAG, "onFileDownloadStatusCompleted。。。。。" + downloadFileInfo.getFileName());
            if (downloadFileInfo == null) {
                return;
            }

            if (downloadFileInfo.getStatus() == Status.DOWNLOAD_STATUS_COMPLETED) {
                if ("zip".equalsIgnoreCase(FileUtil.getFileSuffix(downloadFileInfo.getFileName()))) {// zip
                    File file = new File(MeiYeConfig.FILE_PATH + "/" + downloadFileInfo.getFileName());
                    file.renameTo(new File(MeiYeConfig.FILE_PATH + "/index.zip"));

                    SharedPreferences preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putFloat("js_version", version);
                    Log.e("again",version+"...");
                    editor.putString("js_download_url", download_url);
                    editor.commit();
                }
            } else {
                File file = new File(MeiYeConfig.FILE_PATH + "/" + downloadFileInfo.getFileName());
                file.renameTo(new File(MeiYeConfig.FILE_PATH + "/index.zip"));

                SharedPreferences preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putFloat("js_version", version);
                Log.e("again222",version+"...");
                editor.putString("js_download_url", download_url);
                editor.commit();
            }

            getMd5();

            Log.e("restart", preferences.getFloat("js_version", -1) + "...");
        }

        @Override
        public void onFileDownloadStatusFailed(String url, DownloadFileInfo downloadFileInfo, FileDownloadStatusFailReason failReason) {
            // 下载失败了，详细查看失败原因failReason，有些失败原因你可能必须关心
            Log.e(TAG, "onFileDownloadStatusFailed-------------");

            String failType = failReason.getType();
            String failUrl = failReason.getUrl();// 或：failUrl = url，url和failReason.getType()会是一样的

            if (FileDownloadStatusFailReason.TYPE_URL_ILLEGAL.equals(failType)) {
//                LsToast.show(mContext, "下载失败");
                // 下载failUrl时出现url错误
            } else if (FileDownloadStatusFailReason.TYPE_STORAGE_SPACE_IS_FULL.equals(failType)) {
                LsToast.show(mContext, "存储空间不足");
                // 下载failUrl时出现本地存储空间不足
            } else if (FileDownloadStatusFailReason.TYPE_NETWORK_DENIED.equals(failType)) {
                LsToast.show(mContext, "无法访问网络");
                // 下载failUrl时出现无法访问网络
            } else if (FileDownloadStatusFailReason.TYPE_NETWORK_TIMEOUT.equals(failType)) {
                LsToast.show(mContext, "连接超时");
                // 下载failUrl时出现连接超时
            } else {
//                LsToast.show(mContext, "下载失败");
                // 更多错误....
            }

            // 查看详细异常信息
            Throwable failCause = failReason.getCause();// 或：failReason.getOriginalCause()

            // 查看异常描述信息
            String failMsg = failReason.getMessage();// 或：failReason.getOriginalCause().getMessage()
        }
    };

    private OnDownloadFileChangeListener mOnDownloadFileChangeListener = new OnDownloadFileChangeListener() {
        @Override
        public void onDownloadFileCreated(DownloadFileInfo downloadFileInfo) {
            // 一个新下载文件被创建，也许你需要同步你自己的数据存储，比如在你的业务数据库中增加一条记录
            Log.e(TAG, "onDownloadFileCreated");
        }

        @Override
        public void onDownloadFileUpdated(DownloadFileInfo downloadFileInfo, Type type) {
            // 一个下载文件被更新，也许你需要同步你自己的数据存储，比如在你的业务数据库中更新一条记录
            Log.e(TAG, "onDownloadFileUpdated");

            int totalSize = (int) downloadFileInfo.getFileSizeLong();
            int downloaded = (int) downloadFileInfo.getDownloadedSizeLong();
            int rate = (int) (downloaded * 1.0 / totalSize * 100);
            pb_progressbar.setProgress(rate);
            tv_progressbar.setText("下载进度" + rate + "%");
        }

        @Override
        public void onDownloadFileDeleted(DownloadFileInfo downloadFileInfo) {
            // 一个下载文件被删除，也许你需要同步你自己的数据存储，比如在你的业务数据库中删除一条记录
            Log.e(TAG, "onDownloadFileDeleted");
        }
    };


}
